package com.example.springsecurity.common.filter;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.example.springsecurity.common.config.RedisCache;
import com.example.springsecurity.common.config.SystemUserLoginDetail;
import com.example.springsecurity.common.enums.GlobalExceptionEnum;
import com.example.springsecurity.common.exception.BizException;
import com.example.springsecurity.common.utils.IpUtil;
import com.example.springsecurity.common.utils.JwtTokenUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

import static com.example.springsecurity.common.constant.Constant.AUTHORIZATION;
import static com.example.springsecurity.common.constant.Constant.REDIS_LOGIN_PATH;

/**
 * @Description：JWT认证过滤器
 * @Author：fengcheng
 * @Date：2024/12/19 11:59
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从header中获取token
        String token = request.getHeader(AUTHORIZATION);
        if (StringUtils.isBlank(token)) {
            // 放行
            filterChain.doFilter(request, response);
            return;
        }
        String authHeader = request.getHeader(jwtTokenUtil.getTokenHeader());
        String mobile = null;
        if (authHeader != null) {
            String tokenHead = jwtTokenUtil.getTokenHead();
            if (authHeader.startsWith(tokenHead)) {
                // The part after "Bearer "
                String authToken = authHeader.substring(tokenHead.length());
                // 页面上传过来的token 解析出来的username
                mobile = jwtTokenUtil.getUserNameFromToken(authToken);
                if (StringUtils.isNotBlank(mobile) && SecurityContextHolder.getContext().getAuthentication() == null) {
                    //从redis中获取用户信息
                    String redisKey = REDIS_LOGIN_PATH + mobile;
                    Object cacheObject = redisCache.getCacheObject(redisKey);
                    if (Objects.isNull(cacheObject)) {
                        log.error("用户未登录：{}", mobile);
                        throw new BizException("用户未登录");
                    }
                    SystemUserLoginDetail loginUser = JSON.to(SystemUserLoginDetail.class, cacheObject.toString());
                    // 验证token是否还有效
                    if (jwtTokenUtil.validateToken(authToken, loginUser)) {
                        // 获取权限信息封装到Authentication中, 然后存入SecurityContextHolder
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    } else {
                        throw new BizException(GlobalExceptionEnum.ERROR_TOKEN_EXPIRED.getCode(), GlobalExceptionEnum.ERROR_TOKEN_EXPIRED.getMessage());
                    }
                }
            }
        }
        formMapKey(request, mobile);
        //放行
        filterChain.doFilter(request, response);
    }

    /**
     * @Description：打印接口信息
     * @Author：fengcheng
     * @Date：2025/1/17 17:03
     * @Param：request
     * @Param：mobile
     * @ParamsType：[jakarta.servlet.http.HttpServletRequest, java.lang.String]
     * @Return：void
     */
    private void formMapKey(HttpServletRequest request, String mobile) {
        String ip = IpUtil.getIp(request);
        String fullUrl = request.getRequestURL().toString();
        Map<String, String[]> parameterMap = request.getParameterMap();
        String requestType = request.getMethod();
        String time = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss SSS");
        log.info("接口信息：请求时间:{}, 请求地址:{}, 接口类型:{} , ip:{} ,mobile:{} , 请求参数：{}", time, fullUrl, requestType, ip, mobile, JSON.toJSONString(parameterMap));
    }
}
